package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuQuery;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 */
@Slf4j
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    //@Autowired
    //private StringRedisTemplate stringRedisTemplate; //适合 key和value都是字符串类型

    @Autowired
    private RedisTemplate redisTemplate; //适合值是任意类型

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    //原子性
    @Override
    public int insertProduct(Product product) {
        //1.保存Product对象到product表
        productMapper.insert(product); //主键回填

        //2.保存List<ProductSku>对象到product_sku表
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(product.getId());
            productSkuMapper.insert(productSku);

            //添加商品库存  //3.保存List<SkuStock>对象到sku_stock表
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        //4.保存ProductDetails对象到product_details表
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetails.setProductId(product.getId());
        productDetailsMapper.insert(productDetails);

        return 1;
    }


    @Override
    public Product selectProductById(Long id) {
        //1.根据id查询Product对象
        Product product = productMapper.selectById(id);

        //2.封装扩展字段：查询商品对应多个List<ProductSku>
        //select * from product_sku where product_id =?
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<Long> productSkuIdList = productSkuList.stream().map(productSku -> productSku.getId()).toList();


        // select * from sku_stock where sku_id in (1,2,3,4,5,6)
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        Map<Long, Integer> skuIdToTatalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(productSku -> {
            //返回ProductSku对象，携带了库存数据；
            productSku.setStockNum(skuIdToTatalNumMap.get(productSku.getId()));
        });

        product.setProductSkuList(productSkuList);

        //3.封装扩展字段：商品详情图片List<String>
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        String imageUrls = productDetails.getImageUrls();   //url,url,url
        String[] urls = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.asList(urls));
        //返回Product对象
        return product;
    }


    @Override
    public int updateProduct(Product product) {
        //1.更新Product
        productMapper.updateById(product);

        //2.更新SKU   List<ProductSku>
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        productSkuList.forEach(productSku -> {
            productSkuMapper.updateById(productSku);

            //3.更新库存   List<ProductSku> -> 获取扩展字段stockNum
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        });

        //4.更新详情ProductDetails
        ProductDetails productDetails = productDetailsMapper
                .selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);

        return 1;
    }


    @Override
    public int deleteProductByIds(Long[] ids) {
        //1.删除Product表数据
        // delete from product where id in (1,2)
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //2.删除ProductSku表数据
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, Arrays.asList(ids)));
        List<Long> productSkuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(productSkuIdList);

        //3.删除SkuStock表数据
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        //4.删除ProductDetails表数据
        // delete from product_details where product_id in (1,2)
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, Arrays.asList(ids)));
        return 1;
    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批拒绝");
        }
        productMapper.updateById(product);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);

        //更新bitmap
        //根据spu对象id查询sku集合
        List<ProductSku> list = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        String key = "sku:product:data";

        if (status == 1) {
            product.setStatus(1);
            list.forEach( item -> {
                redisTemplate.opsForValue().setBit(key,item.getId(),true);
            });
        } else {
            product.setStatus(-1);
            list.forEach( item -> {
                redisTemplate.opsForValue().setBit(key,item.getId(),false);
            });
        }
        productMapper.updateById(product);
    }


    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.getTopSale();
    }


    @Override
    public List<ProductSku> skuList(SkuQuery skuQuery) {
        return productSkuMapper.skuList(skuQuery);
    }


    /**
     * 服务提供者：6个接口来服务于商品详情查询。需要进行优化，提供查询效率。
     * 需要使用redis来提高性能。
     */

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            ProductSku productSku = null;
            String dataKey = "product:sku:" + skuId;

            //先判断缓存中是否有数据
            if(redisTemplate.hasKey(dataKey)){
                //如果有,则从缓存中取数据
                productSku =(ProductSku) redisTemplate.opsForValue().get(dataKey);
                System.out.println(Thread.currentThread().getName() + " 从缓存中获取 productSku = " + productSku);
                //返回结果
                return productSku;
            }else{
                //如果缓存中没有数据
                //解决缓存击穿问题,分布式锁
                String lockKey = "product:sku:lock:" + skuId;
                String lockValue = UUID.randomUUID().toString().replaceAll("-","");
                Boolean isFlag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue,1,TimeUnit.MINUTES);
                //如果成功上锁
                if(isFlag){
                    try {
                        //从数据库中取数据
                        productSku = getSkuDataFromDB(skuId);
                        //并添加到缓存中,设置过期时间避免死锁,过期时间随机,避免缓存雪崩
                        long ttl = productSku == null ? 1 : 60 + new Random().nextInt(10);
                        redisTemplate.opsForValue().set(dataKey,productSku,ttl, TimeUnit.MINUTES);
                    } finally {
                        //释放锁,避免释放他人锁
                        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                                "then\n" +
                                "    return redis.call(\"del\",KEYS[1])\n" +
                                "else\n" +
                                "    return 0\n" +
                                "end";
                        redisScript.setScriptText(script);
                        redisScript.setResultType(Long.class); //设置返回值类型
                        redisTemplate.execute(redisScript, Arrays.asList(lockKey), lockValue);
                    }
                }else{
                    System.out.println(Thread.currentThread().getName() + "没抢到锁,在自旋");
                    //如果没抢到锁,自旋重试
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return getProductSku(skuId);
                }
            }
            return productSku;
        } catch (Exception e) {
            log.error(e.getMessage());
            //兜底方法
            return getSkuDataFromDB(skuId);
        }
    }

    private ProductSku getSkuDataFromDB(Long skuId){
        System.out.println("从数据库中取数据");
        return productSkuMapper.selectById(skuId);
    }


    @Override
    public Product getProduct(Long id) {
        String dataKey = "product:prod" + id;
        Product product = null;

        //判断缓存中是否有数据
        if(redisTemplate.hasKey(dataKey)){
            //如果有,则直接从缓存中拿数据
            product = (Product) redisTemplate.opsForValue().get(dataKey);
            return product;
        }else{
            //如果缓存中没有数据,则从数据库中查询
            //使用分布式锁避免缓存穿透等问题
            String lockKey = "product:prod:lock";
            String lockValue = UUID.randomUUID().toString().replaceAll("-","");
            Boolean isFlag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 1, TimeUnit.MINUTES);
            //如果成功上锁
            if(isFlag){
                try {
                    //从数据库中查数据
                    product = getProductFromDB(id);
                    //添加到缓存中
                    int ttl = product == null ? 1 : 60 + new Random().nextInt(10);
                    redisTemplate.opsForValue().set(dataKey,product, ttl,TimeUnit.MINUTES);
                } finally {
                    //释放锁
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                            "then\n" +
                            "    return redis.call(\"del\",KEYS[1])\n" +
                            "else\n" +
                            "    return 0\n" +
                            "end";
                    redisScript.setScriptText(script);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript,Arrays.asList(lockKey),lockValue);
                }
            }else{
                //睡眠+自旋
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getProduct(id);
            }
        }
        return getProductFromDB(id);
    }

    private Product getProductFromDB(Long id) {
        return productMapper.selectById(id);
    }


    @Override
    public SkuPrice getSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice));
        SkuPrice skuPrice = new SkuPrice();
        BeanUtils.copyProperties(productSku, skuPrice);
        return skuPrice;
    }


    @Override
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
    }


    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id).select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }


    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }


    // select * from product_sku where id in (1,2,3)
    // select id,sale_price,market_price from product_sku where id in (1,2,3)
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        //根据sku查询到所有商品的skuId和价格,以及市场价
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList)
                .select(ProductSku::getId, ProductSku::getSalePrice, ProductSku::getMarketPrice));

        //转换类型
        List<SkuPrice> skuPriceList = productSkuList.stream().map(p -> {
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(p.getId());
            skuPrice.setSalePrice(p.getSalePrice());
            skuPrice.setMarketPrice(p.getMarketPrice());
            return skuPrice;
        }).toList();

        return skuPriceList;
    }

    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        String lockKey = "sku:chechAndLock:" + orderNo;
        String dataKey = "sku:lock:data:" + orderNo;
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(lockKey, orderNo, 1, TimeUnit.HOURS);
        if(!isExist){
            if(redisTemplate.hasKey(dataKey)){
                return "";
            }else{
                return "重复提交";
            }
        }
        //遍历所有商品,验库存并锁库存,需要具有原子性
        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum()); // 查询库存数据，增加数据库行锁   for update
            if(skuStock==null){
                skuLockVo.setIsHaveStock(false);
            }else{
                skuLockVo.setIsHaveStock(true);
            }
        }
//        skuLockVoList.forEach(skuLockVo -> {
//            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
//            //如果没有一个符合,就验库存失败
//            if(skuStock == null){
//                skuLockVo.setIsHaveStock(false);
//            }else{
//                skuLockVo.setIsHaveStock(true);
//            }
//        });

        //只要有一个商品锁定失败,所有锁定的商品都要解锁库存
        if(skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.getIsHaveStock())){
            //获取所有锁定成功的商品,遍历解锁库存
            StringBuilder stringBuilder = new StringBuilder();
            List<SkuLockVo> noHaveStockSkuLockVo = skuLockVoList.stream().filter(skuLockVo -> !skuLockVo.getIsHaveStock()).toList();
            for (SkuLockVo skuLockVo : noHaveStockSkuLockVo) {
                stringBuilder.append("商品: 【 " + skuLockVo.getSkuId() + " 】 库存不足;");
            }
            redisTemplate.delete(lockKey);
            return stringBuilder.toString();
        }else{
            for (SkuLockVo skuLockVo : skuLockVoList) {
                int count = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
                if(count == 0){
                    redisTemplate.delete(lockKey);
                    //假设存在锁库存失败情况，事务回滚
                    throw new ServiceException("锁库存失败");
                }
            }
//            skuLockVoList.forEach(skuLockVo -> {
//                int row = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
//                if(row == 0){
//                    redisTemplate.delete(lockKey);
//                    throw new ServiceException("库存锁定失败");
//                }
//            });
        }
        //如果所有商品都锁定成功,则将锁定信息缓存,以方便解锁库存或减库存
        redisTemplate.opsForValue().set(dataKey,skuLockVoList);
        return "";
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void unlock(String orderNo) {
        String lockKey = "sku:lock:" + orderNo;
        String dataKey = "sku:lock:data:" + orderNo;
        //业务去重,防止重复消费
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(lockKey, orderNo, 1, TimeUnit.HOURS);
        if(!isExist){
            return;
        }
        //获取锁定库存的缓存信息
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if(CollectionUtils.isEmpty(skuLockVoList)){
            return;
        }

        //解锁库存
        skuLockVoList.forEach(skuLockVo -> {
            int row = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if(row == 0){
                //解除去重
                redisTemplate.delete(lockKey);
                throw new ServiceException("解锁出库失败");
            }
        });

        //解除库存后,删除锁定库存的缓存,防止重复解锁库存
        redisTemplate.delete(dataKey);

    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void minus(String orderNo) {
        String lockKey = "sku:minus:" + orderNo;
        String dataKey = "sku:lock:data:" + orderNo;

        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(lockKey, orderNo, 1,TimeUnit.HOURS);
        if(!isExist){
            return;
        }
        List<SkuLockVo> skuLockVoockList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if(CollectionUtils.isEmpty(skuLockVoockList)){
            return;
        }
        skuLockVoockList.forEach(skuLockVo -> {
            int row = skuStockMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if(row == 0){
                redisTemplate.delete(lockKey);
                throw new ServiceException("减出库失败");
            }
        });
        redisTemplate.delete(dataKey);
    }


}